// pages/post/create_post/create_post.js
let util = require('../../../utils/content_check.js')
const { formatTime } = require('../../../utils/util.js')
const app = getApp()
var total = [];
var tempFilePaths;
var uid;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: [],
    _num:3,
    suggestsList:[],
    isOverdue: null,
    isExchanged: null,
    title: '',
    content: '',
    category:null,
    statusflag:0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var category = options.category
    this.setData({
      category: category
    })
    //闲物置换默认为1 未置换
    if(category==1){
      this.setData({
        statusflag: 1
      })
    }
  },

  // 选择图片
  chooseImg: function(){
    var that = this;
    wx.chooseImage({
      count: 3, 
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'],
      success: function (res) {
        tempFilePaths = res.tempFilePaths
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.uploadFile2(tempFilePaths, 0);
        var uploadedImageLists = that.data.imageUrl;
        var totalImages = uploadedImageLists.concat(res.tempFilePaths);
        var aNum = 0;
        if (totalImages.length >= 3) {
          totalImages.length = 3;
          aNum = 1;
        }
        that.setData({
          num: 0,
          addNum: aNum,
          imageUrl: totalImages
        })
      }
    })
  },
  uploadFile2: function (file, i) {//递归调用
    var that = this;
    wx.uploadFile({
      url: app.getHeader() +'/SheQu/uploadWxImg', //仅为
      filePath: file[i],
      name: 'img',
      success: function (res) {
        var obj = new Object();
        obj.ind = i + 1;
        var data = res.data;
        console.info(data);
        obj.src = data;
        console.info("--------------*****-------------------");
        console.info(obj);
        if (!((i + 1) == file.length)) {
          total.push(obj);
          that.uploadFile2(file, i + 1);
        } else {
          total.push(obj);
          that.setData({ perImgSrc: total });
        }
      }
    })
  },
  removeImage: function(e){
    var that = this;
    var currentImageLists = that.data.imageUrl; 
    currentImageLists.splice(e.target.dataset.index,1);
    that.setData({
        imageUrl:currentImageLists
    })
    if(currentImageLists.length < 3 && currentImageLists.length >= 1) {
       that.setData({
            addNum: 0
       })
    } else if(currentImageLists.length == 0) {
       that.setData({
            addNum: 1,
            num: 1
       })
    }
  },
  preImage:function(e){
    var that = this;
    var currentImageUrl = that.data.imageUrl[e.target.dataset.index]
    wx.previewImage({
      current: currentImageUrl, // 当前显示图片的http链接
      urls: that.data.imageUrl // 需要预览的图片http链接列表
    })
  },

  beforeRead(event) {
    const { file, callback } = event.detail;
    callback(file.type === 'image');
  },
  afterRead(event){
    var that = this
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: 'https://www.runze.site/prod-api/common/upload', // 仅为示例，非真实的接口地址
      filePath: file.url,
      header:{
        'content-type': 'application/json',
        'Authorization':  app.getToken()
      },
      name: 'file',
      formData: { user: 'test' },
      success(res) {
        console.log("*******",res.data)
        console.log("*******",res)
        // 上传完成需要更新 fileList
        if(res.statusCode==200){
          const { imageUrl = [] } = that.data;
          var tempUrls = res.data.split(",")
          var tempUrl = tempUrls[3].split("\"");
          // console.log(tempUrl)
          imageUrl.push({ ...file, url: tempUrl[3] });
          that.setData({ imageUrl });
        }

      },
    });
  },
  onTitleInput: function (e) {
    var title = e.detail.value;
    this.setData({
      title: title
    })
  },
  onContentInput: function (e) {
    var content = e.detail.value;
    this.setData({
      content: content
    })
  },

  onExchangedChange: function (e){
    var isExchanged = null;
    if(e.detail.value=="false"){
      isExchanged = false
    }else{
      isExchanged = true
    }
    this.setData({
      isExchanged: isExchanged
    })
  },
  onOverdueChange: function (e){
    var isOverdue = null;
    if(e.detail.value=="false"){
      isOverdue = false
    }else{
      isOverdue = true
    }
    this.setData({
      isOverdue: isOverdue
    })
  },

  // 整理数据，提交到缓存，试图写入js文件内
  formSubmit: async function (e){
    // var title = this.data.title
    // var content = this.data.content
    // if(!title){
    //   wx.showToast({
    //     title: '请输入标题',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return
    // }
    // if(!content){
    //   wx.showToast({
    //     title: '请输入内容',
    //     icon: 'none',
    //     duration: 2000
    //   })
    //   return
    // }
    // var isChecked = await util.checkString(title+content)
    // if(!isChecked){
    //   wx.showToast({
    //     icon: 'none',
    //     title: '文字违规',
    //   })
    //   this.setData({
    //     title: '',
    //     content: ''
    //   })
    //   return
    // }else{
    //   var author_info = wx.getStorageSync('user_info')
    //   var author_id = author_info.user_id
    //   var author_name = author_info.user_nickname
    //   var author_pic = author_info.user_pic
    //   var post_id = wx.getStorageSync('posts_list').length
    //   var time = []
    //   var myDate = new Date()
    //   time.push(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds())
    //   var preview = this.data.content.substr(0, 40)
    //   var category = this.data.category
    //   var isOverdue = this.data.isOverdue
    //   var isExchanged = this.data.isExchanged
    //   var post_pic = this.data.imageUrl
    //   var comment_list = []
    //   var post = {
    //     post_id: post_id,
    //     author_id: author_id,
    //     author_name: author_name,
    //     author_pic: author_pic,
    //     time: time,
    //     title: title,
    //     preview: preview,
    //     content: content,
    //     category: category,
    //     isOverdue: isOverdue,
    //     isExchanged: isExchanged,
    //     post_pic: post_pic,
    //     comment_list: comment_list
    //   }
    //   var posts_list = wx.getStorageSync('posts_list')
    //   posts_list.push(post)
    //   wx.setStorageSync('posts_list', posts_list)
    //   wx.navigateTo({
    //     url: '../post_content/post_content?post_id=' + post_id,
    //   })
    // }
    // 上面不是注释掉了 下面的被注释掉了

    // if(util.content_check(title+content)){
    //   console.log('通过内容审核')
    //   {
    //   /*
    //   var author_info = wx.getStorageSync('user_info')
    //   var author_id = author_info.user_id
    //   var author_name = author_info.user_nickname
    //   var author_pic = author_info.user_pic
    //   var post_id = wx.getStorageSync('posts_list').length
    //   var time = []
    //   var myDate = new Date()
    //   time.push(myDate.getFullYear(), myDate.getMonth(), myDate.getDate(), myDate.getHours(), myDate.getMinutes(), myDate.getSeconds())
    //   var preview = this.data.content.substr(0, 40)
    //   var category = this.data.category
    //   var isOverdue = this.data.isOverdue
    //   var isExchanged = this.data.isExchanged
    //   var post_pic = this.data.imageUrl
    //   var comment_list = []
    //   var post = {
    //     post_id: post_id,
    //     author_id: author_id,
    //     author_name: author_name,
    //     author_pic: author_pic,
    //     time: time,
    //     title: title,
    //     preview: preview,
    //     content: content,
    //     category: category,
    //     isOverdue: isOverdue,
    //     isExchanged: isExchanged,
    //     post_pic: post_pic,
    //     comment_list: comment_list
    //   }
    //   var posts_list = wx.getStorageSync('posts_list')
    //   posts_list.push(post)
    //   wx.setStorageSync('posts_list', posts_list)
    //   wx.navigateTo({
    //     url: '../post_content/post_content?post_id=' + post_id,
    //   }) */ }
    // }else{
    //   console.log('未通过内容审核')
    //   console.log(util.content_check(title))
    //   console.log(util.content_check(content))
    //   // if(!util.content_check(title)){
    //   //   // this.setData({
    //   //   //   title: ''
    //   //   // })
    //   // }
    //   // if(!util.content_check(content)){
    //   //   // this.setData({
    //   //   //   content: ''
    //   //   // })
    //   // }
    // }
    var title = this.data.title
    var content = this.data.content
    var images = this.data.imageUrl
    if(images.length>0){
      content = content+"<p>"
      for(var i=0;i<images.length;++i){
        content= content+"<img src=\""+images[i].url+"\">"
      }
      content = content+"</p>"
    }
    // console.log("imageUrl",this.data.imageUrl)
    console.log("content",content)
    var time = formatTime(new Date())
    if(!title){
      wx.showToast({
        title: '请输入标题',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(!content){
      wx.showToast({
        title: '请输入内容',
        icon: 'none',
        duration: 2000
      })
      return
    }
    var newArticle = {
      title:title,
      content:content,
      theme:this.data.category,
      createtime:time,
      statusflag:this.data.statusflag
    }
    console.log("new",newArticle)
    app.sendPostRequest('/bbs/insert',newArticle,(res) => {
      if(res.code == 200){
        wx.showToast({
          title: '发布成功!',
          icon: 'success',
          duration: 2000,
          success:function(){
            setTimeout(function(){
              wx.navigateBack({
                delta: 1,
              },4000)
            })
          }
        })
        
      }
     
    })
  }
  
})